package com.datastructure;

public class MySparseArrayMain {
    public static void main(String[] args) {
        //定义五个节点的稀疏数组，这里的6不包含第一行记录
        MySparseArray[] mySparseArrays = new MySparseArray[6];
        //第一行为记录行数、列数、节点数，下标为0
        //7行、9列
        mySparseArrays[0] = new MySparseArray(7, 9, 6);
        mySparseArrays[1] = new MySparseArray(1, 1, 3);
        mySparseArrays[2] = new MySparseArray(3, 0, 1);
        mySparseArrays[3] = new MySparseArray(3, 1, 4);
        mySparseArrays[4] = new MySparseArray(4, 2, 7);
        mySparseArrays[5] = new MySparseArray(5, 5, 5);

        // 遍历
        for (int i = 0; i < mySparseArrays[0].getRow(); i++) {
            for (int j = 0; j < mySparseArrays[0].getCol(); j++) {
                int k;//这个字段用来记录有值的下标
                //第一行记录为0，要跳过第一行
                for (k = 1; k < mySparseArrays.length; k++) {
                    if (mySparseArrays[k].getRow() == i && mySparseArrays[k].getCol() == j) {
                        break;
                    }
                }
                if (k < mySparseArrays.length) {
                    System.out.print(mySparseArrays[k].getVal() + " ");
                } else {
                    System.out.print(0 + " ");
                }
            }
            //换行
            System.out.println();
        }
    }
}

/**
 * 稀疏数组实现
 */
class MySparseArray {
    //稀疏数组的行数
    private int row;
    //稀疏数组的列数
    private int col;
    //稀疏数组当前行当前列的值
    private int val;

    //通过构造函数实例化
    public MySparseArray(int row, int col, int val) {
        this.row = row;
        this.col = col;
        this.val = val;
    }

    public int getRow() {
        return row;
    }

    public int getCol() {
        return col;
    }

    public int getVal() {
        return val;
    }
}
